package lex.dm.ui.cmd;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;

import org.lex.swing.ActionBuilder;

import lex.dm.DTree;
import lex.dm.utils.Prefs;

public class CommandPane extends JPanel {
	private JToolBar toolBar = null;
	private JButton executeButton = null;
	private JScrollPane scrollPane = null;
	private JTextArea textArea = null;

	public CommandPane() {
		super();
		initialize();
	}

	public void execute(String sql) {
		DTree.getApplication().getContentPane().execute(sql);
	}

	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new BorderLayout());
		this.add(getToolBar(), BorderLayout.NORTH);
		this.add(getScrollPane(), BorderLayout.CENTER);
	}

	private JToolBar getToolBar() {
		if (toolBar == null) {
			toolBar = new JToolBar();
			toolBar.add(getExecuteButton());
		}
		return toolBar;
	}

	private JButton getExecuteButton() {
		if (executeButton == null) {
			ActionBuilder a = new ActionBuilder("Execute");
			a.setActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					execute(getTextArea().getText());
				}
			});
			executeButton = new JButton(a);
		}
		return executeButton;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTextArea());
		}
		return scrollPane;
	}

	private JTextArea getTextArea() {
		if (textArea == null) {
			textArea = new JTextArea("select * from " + Prefs.BREAST_CANCER_WISCONSIN_TABLE);
			textArea.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent e) {
					if (e.getModifiersEx() == KeyEvent.CTRL_DOWN_MASK && e.getKeyCode() == KeyEvent.VK_ENTER)
						execute(textArea.getText());
				}
			});
		}
		return textArea;
	}
}
